﻿using System;
using System.Windows;
using System.Windows.Media;

namespace NthDownload.Common.Utils
{
    public class VisualTreeUtils
    {
        /// <summary>
        /// Searches the visual tree recursively for the first element of a type
        /// </summary>
        /// <param name="type">The type of the element to search for.</param>
        /// <param name="element">The element who's visual tree to search.</param>
        /// <returns></returns>
        public static DependencyObject GetChildElementOfType(Type type, DependencyObject element)
        {
            int childCount = VisualTreeHelper.GetChildrenCount(element);

            for (int i = 0; i < childCount; i++)
            {
                DependencyObject childElement = VisualTreeHelper.GetChild(element, i);

                if (childElement.GetType() == type)
                {
                    return childElement;
                }
            }

            for (int i = 0; i < childCount; i++)
            {
                DependencyObject childElement = VisualTreeHelper.GetChild(element, i);
                DependencyObject returnChild = GetChildElementOfType(type, childElement);

                if (returnChild != null && returnChild.GetType() == type)
                {
                    return returnChild;
                }
            }

            return null;
        }
    }
}
